<template>
  <div class="export-box">
    <a-modal
      :width="width"
      :confirm-loading="spinning"
      v-model:open="open"
      :title="modalTitle"
      :afterClose="afterClose"
      @ok="handleOk"
    >
      <div class="template-box">
        <a-spin :spinning="spinning">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :maxCount="1"
            :multiple="false"
            :before-upload="beforeUpload"
            @remove="handleRemove"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">将文件拖到此处，或<a>点击上传</a></p>
            <p class="ant-upload-hint">
              <!-- Support for a single or bulk upload. Strictly prohibit from uploading company data or
            other band files -->
            </p>
          </a-upload-dragger>
          <p class="tips"
            >仅允许导入xls，xlsx格式文件，文件大小不超过5MB。<a @click="handleDownLoad"
              >下载模板</a
            ></p
          >
        </a-spin>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { defHttp } from '@/utils/http/axios';
  import { defHttp as exportHttp } from '@/utils/http/axios/requestFile';
  import { InboxOutlined } from '@ant-design/icons-vue';
  import { message, Upload } from 'ant-design-vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { watch, ref } from 'vue';
  import type { UploadProps } from 'ant-design-vue';
  // 下载模板
  enum downloadFunc {
    url = 'Binder/template/', //下载默认模板
    // personDownLoad = '/Binder/template/',
  }
  //导出模板地址
  enum importFunc {
    url = 'Binder/import/',
    // importTemplatePerson = '/Binder/import/',
  }
  const props = defineProps({
    modal1Visible: {
      type: Boolean, //类型字符串
      default: false, //如果没有传递msg参数,默认值是这个
    },
    modalTitle: {
      type: String,
      default: '批量导入',
    },
    width: {
      type: Number,
      default: 800,
    },
    type: {
      type: String,
      default: 'commonDownLoad',
    },
    typeImport: {
      type: String,
      default: 'importTemplateStaff',
    },
  });
  watch(
    () => props.modal1Visible,
    (value) => {
      open.value = value;
    },
  );
  watch(
    () => props.type,
    (value) => {
      type = value;
    },
  );
  watch(
    () => props.typeImport,
    (value) => {
      typeImport = value;
    },
  );
  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  };
  const emit = defineEmits(['close']);
  const modalTitle = props.modalTitle;
  let type = props.type;
  let typeImport = props.typeImport;
  const open = ref(false);
  const fileList: any = ref([]);
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const result = checkFileType(file);
    if (!result) return Upload.LIST_IGNORE;
    if (file.type) fileList.value = [...(fileList.value || []), file];

    return false;
  };
  const checkFileType = (file) => {
    let result = true;
    const isXlS =
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel';
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isXlS) {
      result = false;
      message.error('仅支持xls、xlsx格式的文件!');
    }
    if (!isLt2M) {
      result = false;
      message.error('上传文件大小不能超过 5MB!');
    }
    return result;
  };
  const handleDownLoad = () => {
    downloadByBase64();
  };
  const handleOk = () => {
    // const formData = new FormData();
    // fileList.value.forEach((file: UploadProps['fileList'][number]) => {
    //   importByBase64({ file: file.originFileObj });
    //   formData.append('files[]', file as any);
    // });
    const file = fileList.value[0];
    if (!fileList.value[0]) {
      message.error('请上传导入文件');
      return false;
    }
    importByBase64({ file: file.originFileObj });
    spinning.value = true;
  };
  const afterClose = () => {
    fileList.value = [];
    emit('close', false);
  };
  const spinning = ref(false);
  const downloadByBase64 = () => {
    let url = downloadFunc.url + type;
    spinning.value = true;
    exportHttp
      .get({ url })
      .then(() => {
        message.success('模板下载成功！');
      })
      .finally(() => {
        spinning.value = false;
      });
  };
  const importByBase64 = (formData) => {
    let url = importFunc.url + type;
    spinning.value = true;
    defHttp
      .post({
        url,
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(() => {
        message.success('数据解析成功！');
        emit('close', false);
      })
      .finally(() => {
        spinning.value = false;
      });
  };
</script>
<style lang="less" scoped>
  .template-box {
    box-sizing: border-box;
    width: 100%;
    padding: 20px;
  }

  .tips {
    height: 40px;
    font-size: 14px;
    font-weight: bold;
    line-height: 40px;
  }
</style>
